import { app, BrowserWindow, ipcMain, WebContentsView } from 'electron';
import { fileURLToPath } from 'url';
import path from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: `${__dirname}/preload.js`,
        },
    });

    win.loadFile('index.html');
};

app.on('ready', () => {
    createWindow();
});

app.on('window-all-closed', () => {
    app.quit();
});

ipcMain.on('maximize', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    win?.maximize();
});

ipcMain.on('minimize', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    win?.minimize();
});

ipcMain.on('closeWindow', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    win?.close();
});

ipcMain.on('fullScreen', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    win?.setFullScreen(!win?.isFullScreen());
});

ipcMain.on('restore', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender);
    win?.restore();
});

ipcMain.on('openWindow', (event) => {
    const win = new BrowserWindow({
        width: 500,
        height: 400,
    });

    win.loadURL('https://ai.com');
});

ipcMain.on('openModal', (event) => {
    const win = new BrowserWindow({
        parent: BrowserWindow.fromWebContents(event.sender)!,
        modal: true,
        width: 400,
        height: 300,
    });

    win.loadURL('https://ai.com');
});

ipcMain.on('openUnframe', (event) => {
    const win = new BrowserWindow({
        frame: false,
        width: 500,
        height: 400,
    });

    win.loadURL('https://ai.com');
});

ipcMain.on('openTransparent', (event, opacity) => {
    const win = new BrowserWindow({
        frame: false,
        transparent: true,
        opacity,
        width: 500,
        height: 400,
    });

    win.loadURL('https://ai.com');
});

ipcMain.on('openView', (event) => {
    const activeWin = BrowserWindow.fromWebContents(event.sender)!;
    const view = new WebContentsView();
    activeWin.contentView.addChildView(view);
    view.webContents.loadURL('https://ai.com');
    view.setBounds({ x: 0, y: 200, width: 800, height: 300 });
    activeWin.on('resize', () => {
        view.setBounds({ x: 0, y: 200, width: activeWin.getContentBounds().width, height: 300 });
    });
});

